'use client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import Image from 'next/image'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import LockIcon from '@/assets/icons/lock.svg'

import { useEffect, useState, useMemo } from 'react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertCircle, X } from 'lucide-react'
import { CustomDialog } from '@/components/CustomDialog'
import AudioSettings from './AudioSettings'
import { useVideoStore, type Option } from '@/stores/video'
import { useAuthStore } from '@/stores/auth'
import FileSelector from './FileSelector'
import { videoService } from '@/services/api/video'
import { type FileItem } from '@/stores/fileStore'
import SearchableSelect from '@/components/SearchableSelect'
import { useGlobalMethods } from '@/hooks/useGlobalMethods'
import { cn } from '@/lib/utils'
import { showAlertDialog } from '@/hooks/showAlertDialog'
import { Textarea } from '@/components/ui/textarea'

interface ValidationRule {
  required?: boolean
  message?: string
  validator?: (value: string) => boolean | string
}

interface FormField {
  label: string
  key: string
  type: 'select' | 'file' | 'audio' | 'button'
  showTooptip?: boolean
  search?: boolean
  clearable?: boolean
  // options?: { value: string; label: string }[]
  options?: Option[]
  extraButton?: string
  validation?: ValidationRule
  hidden?: boolean
}

const defFormFields: FormField[] = [
  {
    label: 'Copywriting style',
    key: 'character',
    type: 'select',
    options: [],
    validation: {
      required: false,
      message: 'Please select copywriting style',
    },
  },
  {
    label: 'Release language',
    key: 'language',
    type: 'select',
    options: [],
    validation: {
      required: true,
      message: 'Please select release language',
    },
  },
  {
    label: 'Release region',
    key: 'hot_topic_area_id',
    type: 'select',
    options: [],
    search: true,
    // extraButton: '点击查看热点地区',
    validation: {
      required: false,
      message: 'Please select release region',
    },
  },
  {
    label: 'Hot topic',
    key: 'hot_topic_id',
    type: 'select',
    showTooptip: false,
    options: [],
    validation: {
      required: false,
      message: 'Please select hot topic',
    },
    hidden: true,
  },
  {
    label: 'Generate sound',
    key: 'tone_id',
    type: 'button',
    extraButton: 'Please select audio file',
    validation: {
      required: false,
      message: 'Please select audio file',
      validator: (value) => {
        const isAudioFile = value.match(/\.(mp3|wav|ogg)$/i)
        return isAudioFile ? true : 'Please upload the correct audio format file'
      },
    },
  },
  {
    label: 'Upload face image',
    key: 'face_image_url',
    type: 'file',
    clearable: true,
    extraButton: 'Example',
    validation: {
      required: false,
      message: 'Please upload face image',
      validator: (value) => {
        const isImageFile = value.match(/\.(jpg|jpeg|png)$/i)
        return isImageFile ? true : 'Please upload the correct image format file'
      },
    },
  },
  {
    label: 'Upload original video',
    key: 'video_url',
    type: 'file',
    clearable: true,
    extraButton: 'Example',
    validation: {
      required: false,
      message: 'Please upload original video',
      validator: (value) => {
        const isVideoFile = value.match(/\.(mp4|mov|avi)$/i)
        return isVideoFile ? true : 'Please upload the correct video format file'
      },
    },
  },
]

export function FormSection({
  commit,
  formSectionParams,
  setFormInfo,
}: {
  commit: (v: any) => void
  setFormInfo: (v: any) => void
  formSectionParams: any
}) {
  const { handlePreview } = useGlobalMethods()
  const { authList } = useAuthStore()
  const [openFileSelector, setOpenFileSelector] = useState(false)
  const [selectedValues, setSelectedValues] = useState<any>({})
  // const [tipsValue, setTipsValue] = useState<Record<string, string>>({})
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [globalError, setGlobalError] = useState<string>('')
  const [formFields, setFormFields] = useState<FormField[]>(defFormFields)
  const {
    systemConfig,
    regionList,
    hotTopicList: hotTopicListStore,
  } = useVideoStore()
  const [key, setKey] = useState('')
  const [hotTopicAreaHistoryItem, setHotTopicAreaHistoryItem] =
    useState<Option | null>(null)
  const { fetchSystemConfig, fetchRegionList, fetchToneList, fetchHotTopicList } =
    useVideoStore()

  const hotTopicList = useMemo(() => {
    if (
      hotTopicAreaHistoryItem !== null &&
      !hotTopicListStore.some((item) => item.value === hotTopicAreaHistoryItem.value)
    ) {
      return [hotTopicAreaHistoryItem, ...hotTopicListStore]
    }
    return hotTopicListStore
  }, [hotTopicListStore, hotTopicAreaHistoryItem])

  const setDedault = async () => {
    if (formSectionParams?.id) {
      if (formSectionParams.hot_topic) {
        await fetchHotTopicList(formSectionParams.hot_topic_area_id)
      }
      const hotRegionItem = formFields.find((item) => item.key === 'hot_topic_id')
      if (formSectionParams.hot_topic && hotRegionItem) {
        hotRegionItem.hidden = false
      }

      const audioLabel = formSectionParams.tone?.names?.zh || ''
      const item: any = formSectionParams.hot_topic
      setHotTopicAreaHistoryItem(
        item
          ? {
              label: `${item?.word}(${item?.zh_word})(${item?.score})`,
              label_zh: item?.zh_word,
              value: item?.id !== undefined ? item.id + '' : '',
            }
          : null,
      )
      setFormFields([...formFields])
      setSelectedValues({
        ...formSectionParams,
        hot_topic_area_id: String(formSectionParams.hot_topic_area_id || ''),
        hot_topic_id: String(formSectionParams.hot_topic ?? ''),
        audioLabel,
        tone_id: String(formSectionParams.tone_id || ''),
      })
    }
  }
  useEffect(() => {
    setDedault()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formSectionParams])
  useEffect(() => {
    if (systemConfig) {
      return
    }
    fetchSystemConfig()
    fetchRegionList()
    fetchToneList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 设置表单字段
  useEffect(() => {
    setFormFields((prevFields) => {
      const newFields = [...prevFields]

      // 设置语言选项
      const langItem = newFields.find((item) => item.key === 'language')
      if (langItem && systemConfig) {
        langItem.options = systemConfig.language
      }

      // 设置角色选项
      const characterItem = newFields.find((item) => item.key === 'character')
      if (characterItem && systemConfig) {
        characterItem.options = systemConfig.character
      }

      // 设置区域选项
      const regionItem = newFields.find((item) => item.key === 'hot_topic_area_id')
      // console.log('regionList:', regionList)
      if (regionItem) {
        regionItem.options = regionList
      }

      // 设置热点话题选项
      const hotRegionItem = newFields.find((item) => item.key === 'hot_topic_id')
      if (hotRegionItem) {
        hotRegionItem.options = hotTopicList
      }

      return newFields
    })
  }, [systemConfig, regionList, hotTopicList, hotTopicAreaHistoryItem])

  const updateHotRegion = (value: string) => {
    const hotRegionItem = formFields.find((item) => item.key === 'hot_topic_id')
    if (hotRegionItem) {
      hotRegionItem.hidden = !value
    }
    setHotTopicAreaHistoryItem(null)
    setFormFields([...formFields])
    setSelectedValues((prevValues: any) => ({
      ...prevValues,
      hot_topic_id: '',
    }))

    fetchHotTopicList(value)
  }

  useEffect(() => {
    setFormInfo({
      face_image_url: selectedValues?.face_image_url ?? '',
      video_url: selectedValues?.video_url ?? '',
      vol: selectedValues?.vol ?? '',
      speed: selectedValues?.speed ?? '',
      tone_id: selectedValues?.tone_id ?? '',
    })
  }, [selectedValues, setFormInfo])

  const handleClick = (_fieldItem: FormField) => {}
  const handleCusValue = (checkItem: Option) => {
    const currentList: Option[] = selectedValues.character || []

    if (currentList.some((item) => item.label === '_CUS_')) {
      const cusItem = currentList.find((item) => item.label === '_CUS_')!
      cusItem.value = checkItem.value
      // 删除逻辑
    } else {
      // 添加
      currentList.push({
        label: checkItem.label,
        value: checkItem.value,
      })
    }
    handleChange('character', currentList)
  }

  const handlePickIteem = (checkItem: Option) => {
    const currentList: Option[] = selectedValues.character || []
    let newList: Option[] = [...currentList]
    if (currentList.some((item) => item.value === checkItem.value)) {
      // 删除逻辑
      newList = currentList.filter((item) => item.value !== checkItem.value)
    } else {
      // 添加
      newList.push({
        label: checkItem.label,
        value: checkItem.value,
      })
    }
    handleChange('character', newList)
  }

  const handleChange = (key: string, value: any) => {
    console.log('🚀 ~ handleChange ~ key:', key)
    console.log('🚀 ~ handleChange ~ value:', value)

    setSelectedValues((prevValues: any) => ({
      ...prevValues,
      [key]: value,
    }))
    if (key === 'hot_topic_area_id') {
      updateHotRegion(value)
    }
    // 清除该字段的错误
    setErrors((prevErrors) => {
      const newErrors = { ...prevErrors }
      delete newErrors[key]
      return newErrors
    })
    setGlobalError('')
  }

  const validateForm = () => {
    const newErrors: Record<string, string> = {}
    let hasError = false

    formFields.forEach((field) => {
      const value = selectedValues[field.key] || ''
      const validation = field.validation

      if (validation) {
        if (validation.required && !value) {
          newErrors[field.key] = validation.message || `${field.label}不能为空`
          hasError = true

          console.log('field.key1', field.key)
        }
      }
    })

    setErrors(newErrors)
    if (hasError) {
      setGlobalError('请完善所有必填项')
      return false
    }

    return true
  }

  const handleSubmit = async () => {
    console.log('selectedValues:', selectedValues)
    if (validateForm()) {
      const { audioLabel, ...sendSelectValue } = selectedValues
      const params = {
        ...sendSelectValue,
        vol: Number(selectedValues.vol),
        video_creation_no: selectedValues?.video_creation?.no || '',
        tone_id: selectedValues.tone_id,
        hot_topic_id: selectedValues?.hot_topic_id ?? '',
        hot_topic_area_id: selectedValues.hot_topic_area_id ?? '',
      }
      const data = await videoService.generateValue(params)
      commit(data)
    } else {
      console.log('Form validation failed')
    }
  }

  const noFaceAuth = useMemo(() => {
    return authList[0]?.has_view === false
  }, [authList])

  const handleShowFileSelector = (field: FormField) => {
    console.log('authList:', authList)
    if (field.key === 'face_image_url' && noFaceAuth) {
      showAlertDialog({
        title: '',
        description: (
          <div>
            If you need to use it, please contact your department leader. After
            review by the department leader, it will be summarized to AI Matrix
            Marketing for permission activation.
          </div>
        ),
        confirmText: <div>Confirm</div>,
      })
      return
    }
    setOpenFileSelector(true)
    setKey(field.key)
  }

  const getFieldError = (key: string) => {
    return errors[key] ? (
      <span className="text-xs text-red-500 mt-1">{errors[key]}</span>
    ) : null
  }

  return (
    <div className="w-[336px] h-full flex flex-col gap-4 pl-4">
      <div className="flex-1 relative z-0 bg-white/10 border border-[#B9AEFF]/10 rounded-[14px]">
        <div className="overflow-y-auto flex flex-col gap-4 p-4 absolute z-0 inset-0 my-scrollbar">
          <span className="text-sm text-white/80">Setting</span>
          {formFields.map((field, index) => {
            if (field.hidden) {
              return null
            }
            if (field.key === 'character') {
              return (
                <div key={index} className="flex flex-col gap-4">
                  <label className="text-sm pt-2 text-white/60">
                    {field.validation?.required && (
                      <span className="text-red-500 mr-1">*</span>
                    )}
                    {field.label}
                  </label>
                  <div className="flex-1 flex flex-wrap gap-2">
                    {field.options?.map((item, index) => {
                      return (
                        <span
                          key={item.label + index}
                          onClick={() => handlePickIteem(item)}
                          className={cn(
                            'cursor-pointer bg-black/40 text-sm border border-transparent rounded-lg px-2.5 py-1',
                            selectedValues.character?.some(
                              (cItem: Option) => cItem.value === item.value,
                            )
                              ? 'bg-black/40 text-[#AEA0FF] border-[#AEA0FF]'
                              : 'bg-black/40 text-white/80',
                          )}
                        >
                          {item.label}
                        </span>
                      )
                    })}
                    <Textarea
                      placeholder="Customize"
                      value={
                        selectedValues.character?.find(
                          (cItem: Option) => cItem.label === '_CUS_',
                        )?.value || ''
                      }
                      onChange={(e) => {
                        handleCusValue({
                          label: '_CUS_',
                          value: e.target.value,
                        })
                      }}
                      className="mt-2.5 min-h-[38px] resize-none my-scrollbar border-transparent focus:border-white bg-black/40 rounded-[10px] p-2.5 placeholder:text-white/40"
                    />
                  </div>
                </div>
              )
            }
            if (field.type === 'button') {
              return (
                <div key={index} className="flex flex-col gap-4">
                  <label className="text-sm pt-2 text-white/60">
                    {field.label}
                    {field.validation?.required && (
                      <span className="text-red-500 mr-1">*</span>
                    )}
                  </label>
                  <div className="flex-1">
                    {field.key === 'tone_id' ? (
                      <CustomDialog
                        title="Sound Selection"
                        className="max-w-md"
                        trigger={
                          <div key={field.key}>
                            <Button
                              onClick={() => handleClick(field)}
                              className="w-full border border-[#B9AEFF] bg-black/40 rounded-[10px] text-white"
                              size="sm"
                              variant="outline"
                            >
                              {selectedValues?.audioLabel
                                ? selectedValues.audioLabel
                                : selectedValues?.tone_id
                                  ? `Audio ID:${selectedValues.tone_id}`
                                  : field.extraButton}
                            </Button>
                          </div>
                        }
                        fnChildren={(handleCancel) => (
                          <AudioSettings
                            defVal={{
                              vol: selectedValues?.vol,
                              speed: selectedValues?.speed,
                              tone_id: selectedValues?.tone_id,
                            }}
                            confirm={(value) => {
                              setSelectedValues({
                                ...selectedValues,
                                ...value,
                              })
                              setGlobalError('')
                            }}
                            cancelClick={handleCancel}
                          ></AudioSettings>
                        )}
                      ></CustomDialog>
                    ) : (
                      <Button
                        onClick={() => handleClick(field)}
                        className="w-full"
                        size="sm"
                        variant="outline"
                      >
                        {field.extraButton}
                      </Button>
                    )}
                  </div>
                </div>
              )
            }
            return (
              <div key={index} className="flex flex-col gap-4">
                <label className="text-sm pt-2 text-white/60 flex items-center justify-between">
                  <span>
                    {field.label}
                    {field.validation?.required && (
                      <span className="text-red-500 mr-1">*</span>
                    )}
                  </span>
                  {field.key === 'face_image_url' && field.extraButton && (
                    <Dialog>
                      <DialogTrigger className="text-[#A091FD] h-5 text-sm">
                        {field.extraButton}
                      </DialogTrigger>
                      <DialogContent className="max-w-md p-8">
                        <DialogHeader>
                          <DialogTitle className="text-white text-lg">
                            Face Profile Picture
                          </DialogTitle>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                          <div className="flex items-center justify-center">
                            <Image
                              src="/img/face-example.png"
                              alt="face-example"
                              className="w-32 h-32 rounded-lg"
                              width={128}
                              height={128}
                              priority
                            />
                          </div>
                          <div>
                            <h3 className="text-sm text-white/60 mb-2.5">
                              Standards
                            </h3>
                            <ul className="list-disc pl-4 space-y-1 text-sm text-white/80">
                              <li>
                                Facing the camera, the whole face is not shielded,
                                and the forehead is exposed ;
                              </li>
                              <li>
                                Face accounted for more than 3/4 of the vertical
                                proportion of the picture ;
                              </li>
                              <li>Uniform light, high definition, no watermark.</li>
                            </ul>
                          </div>
                        </div>
                      </DialogContent>
                    </Dialog>
                  )}
                  {field.key === 'video_url' && field.extraButton && (
                    <Dialog>
                      <DialogTrigger className="text-[#A091FD] h-5 text-sm">
                        {field.extraButton}
                      </DialogTrigger>
                      <DialogContent className="max-w-md">
                        <DialogHeader>
                          <DialogTitle>Original Video</DialogTitle>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                          <div className="flex items-center justify-center">
                            <Image
                              src="/img/video-example.gif"
                              alt="video-example"
                              className="h-44 w-80 rounded-lg"
                              width={320}
                              height={176}
                              priority
                            />
                          </div>
                          <div>
                            <h3 className="text-sm text-white/60 mb-2.5">
                              Standards
                            </h3>
                            <ul className="list-disc pl-4 space-y-1 text-sm text-white/80">
                              <li>
                                Original video in high definition, without subtitles
                                or watermarks;
                              </li>
                              <li>
                                Static shots, characters facing the camera,
                                objects/hands not covering the mouth, and head
                                shaking should not be too large;
                              </li>
                              <li>
                                The overall lighting of the original video material
                                is uniform to avoid obvious flickering;
                              </li>
                              <li>
                                Shoot the face of the person in the video in
                                parallel, and avoid shooting from above or below;
                              </li>
                              <li>
                                The best horizontal ratio of the face to the screen
                                is 1/4;
                              </li>
                            </ul>
                          </div>
                        </div>
                      </DialogContent>
                    </Dialog>
                  )}
                </label>
                {field.type === 'select' ? (
                  <div className="flex-1">
                    {field.search ? (
                      <SearchableSelect
                        options={field.options!}
                        placeholder={field.label}
                        value={selectedValues[field.key]}
                        onValueChange={(value) => handleChange(field.key, value)}
                      />
                    ) : (
                      <Select
                        onValueChange={(value) => handleChange(field.key, value)}
                        value={selectedValues[field.key]}
                      >
                        <SelectTrigger
                          className={`w-full bg-black/40 rounded-[10px] text-white/40 ${errors[field.key] ? 'border-red-500' : ''}`}
                        >
                          <SelectValue placeholder={field.label} />
                        </SelectTrigger>
                        <SelectContent>
                          {field.options?.map((option) => (
                            <SelectItem key={option.value} value={option.value}>
                              {field.showTooptip ? (
                                <TooltipProvider delayDuration={200}>
                                  <Tooltip>
                                    <TooltipTrigger asChild>
                                      <p>{option?.label}</p>
                                    </TooltipTrigger>
                                    <TooltipContent align="end" data-side="right">
                                      <p>{option?.label_zh}</p>
                                    </TooltipContent>
                                  </Tooltip>
                                </TooltipProvider>
                              ) : (
                                option.label
                              )}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                    {getFieldError(field.key)}
                    {field.extraButton && (
                      <Button
                        variant="link"
                        className="text-blue-500 h-auto p-0 mt-1 text-sm"
                      >
                        {field.extraButton}
                      </Button>
                    )}
                  </div>
                ) : (
                  <div className="flex-1">
                    <div
                      className={cn(
                        'relative w-full min-h-16 border border-[#A091FD] rounded-[10px] flex flex-col items-center justify-center bg-black/40',
                        errors[field.key] ? 'border-red-500' : '',
                      )}
                    >
                      {field.clearable && selectedValues[field.key] && (
                        <X
                          className="h-4 w-4 opacity-70 cursor-pointer absolute top-2 right-2"
                          onClick={(e) => {
                            e.preventDefault()
                            e.stopPropagation()
                            handleChange(field.key, '')
                          }}
                        />
                      )}
                      <Button
                        onClick={() => handleShowFileSelector(field)}
                        variant="ghost"
                        size="sm"
                        className="text-sm text-white/40"
                      >
                        {field.key === 'face_image_url' && noFaceAuth && (
                          <LockIcon width="16" height="16"></LockIcon>
                        )}
                        Upload
                      </Button>
                      {selectedValues.face_image_url &&
                        field.key === 'face_image_url' && (
                          <img
                            className="cursor-pointer h-10 min-w-10 w-auto bg-black"
                            src={selectedValues.face_image_url}
                            alt=""
                            onClick={() => {
                              handlePreview({
                                title: 'Preview Image',
                                url: selectedValues.face_image_url,
                                type: 'image',
                              })
                            }}
                          />
                        )}
                      {selectedValues.video_url && field.key === 'video_url' && (
                        <video
                          className="cursor-pointer h-10 w-auto bg-black"
                          onClick={() => {
                            handlePreview({
                              title: 'Preview Video',
                              url: selectedValues.video_url,
                              type: 'video',
                            })
                          }}
                          src={selectedValues.video_url}
                        />
                      )}
                      {getFieldError(field.key)}
                    </div>
                  </div>
                )}
              </div>
            )
          })}
          {globalError && (
            <Alert variant="destructive" className="mb-4">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{globalError}</AlertDescription>
            </Alert>
          )}
        </div>
      </div>
      <div className="mb-5 flex justify-end items-center px-6">
        <Button
          onClick={handleSubmit}
          className="h-11 w-full rounded-full text-base"
        >
          Generate Video
        </Button>
      </div>
      <CustomDialog
        showFooter={false}
        open={openFileSelector}
        onOpenChange={setOpenFileSelector}
        title="Select File"
        className="max-w-lg p-8"
        fnChildren={(handleCancel) => (
          <FileSelector
            fType={key === 'face_image_url' ? 'image' : 'video'}
            onConfirm={(v: FileItem) => {
              setSelectedValues((prevValues: any) => ({
                ...prevValues,
                [key]: v.url,
              }))
              handleCancel()
            }}
            onCancel={() => {
              handleCancel()
            }}
          ></FileSelector>
        )}
      ></CustomDialog>
    </div>
  )
}
